package com.ruoyi.kjy.controller;

import java.util.*;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

//import cn.easyes.core.biz.PageInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.MyMesssage;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.kjy.config.FanoutExchangeDemoConfig;
import com.ruoyi.kjy.domain.Demand;
import com.ruoyi.kjy.service.IDemandService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
//import org.springframework.amqp.core.AcknowledgeMode;
//import org.springframework.amqp.core.AmqpTemplate;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.kjy.domain.Achievement;
import com.ruoyi.kjy.service.IAchievementService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;

/**
 * 科技成果管理Controller
 *
 * @author ruoyi
 * @date 2023-04-06
 */
@Api(tags = "成果")
@RestController
@RequestMapping("/achievement")
//public class AchievementController extends BaseController implements ChannelAwareMessageListener {
    public class AchievementController extends BaseController  {
    @Autowired
    private IAchievementService achievementService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private IDemandService demandService;
//    @Resource
//    private AmqpTemplate amqpTemplate;
//    /**
//     * 查询科技成果管理列表a
//     */
//    @GetMapping("/listes")
//    public AjaxResult listes(Integer current, Integer size,Achievement achievement) {
//        if (Objects.isNull(current)) {
//            current = 1;
//        }
//        if (Objects.isNull(size)) {
//            size = 10;
//        }
//        if (size >= 20) {
//            size = 20;
//        }
//        return AjaxResult.success(achievementService.espage(current, size, achievement));
//    }

    /**
     * 查询科技成果管理列表
     * @param current
     * @param size
     * @param achievement
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(Integer current, Integer size,Achievement achievement) {
        if (Objects.isNull(current)) {
            current = 1;
        }
        if (Objects.isNull(size)) {
            size = 10;
        }
        if (size >= 20) {
            size = 20;
        }
        return AjaxResult.success(achievementService.page(current, size, achievement));
    }
    @ApiOperation("点击进入成果详情，推荐相同的成果")
    @GetMapping("/recommend")
    public AjaxResult recommend(String achievementId) {
        Achievement byId = achievementService.getById(achievementId);
        Integer current = 1;
        Integer size = 10;
        String title = byId.getTitle();
        Achievement achievement = new Achievement();
        // 只推荐状态为已审核的数据
        achievement.setState(1);
        achievement.setSearchWord(title);
        IPage<Achievement> page = achievementService.page(current, size, achievement);
        List<Achievement> list = page.getRecords();
        for (Achievement achievement1 : list) {
            if (achievementId.equals(String.valueOf(achievement1.getId()))){
                list.remove(achievement1);
                break;
            }
        }
        return AjaxResult.success(page);
    }


    @ApiOperation("发布成果，推送需求")
    @GetMapping("/recommendDemand")
    public AjaxResult recommendDemand(String achievementId) {
        Achievement byId = achievementService.getById(achievementId);
        Integer current = 1;
        Integer size = 10;
        String title = byId.getTitle();
        Demand demand = new Demand();
        // 只推荐状态为已审核的数据
        demand.setState(1);
        demand.setSearchWord(title);
        IPage<Demand> page = demandService.page(current, size, demand);
        return AjaxResult.success(page.getRecords());
    }

    /**
     * 导出科技成果管理列表
     */
    @Log(title = "科技成果管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Achievement achievement) {
        QueryWrapper<Achievement> queryWrapper = new QueryWrapper<>();
        queryWrapper.setEntity(achievement);
        List<Achievement> list = achievementService.list(queryWrapper);
        ExcelUtil<Achievement> util = new ExcelUtil<Achievement>(Achievement.class);
        util.exportExcel(response, list, "科技成果管理数据");
    }

    /**
     * 获取科技成果管理详细信息
     */
    @ApiOperation("详情")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Achievement byId = achievementService.getById(id);
        R<SysUser> userinfoById = remoteUserService.getUserinfoById(byId.getAuthor(), SecurityConstants.INNER);
        byId.setUser(userinfoById.getData());
        return success(byId);
    }

    /**
     * 新增科技成果管理
     */
    @ApiOperation("发布")
    @Log(title = "科技成果管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Achievement achievement) throws IOException {
        achievement.setAuthor(SecurityUtils.getLoginUser().getUserid());
        String nickName = SecurityUtils.getLoginUser().getSysUser().getNickName();
        if (nickName==null) {
            throw new ServiceException("用户昵称为空");
        }
        achievement.setAuthorName(nickName);
        achievement.setReleaseTime(new Date());
        achievement.setCreateTime(new Date());
        achievement.setState(0);
        boolean save = achievementService.save(achievement);
        //推送部分
        AjaxResult ajaxResult = recommendDemand(String.valueOf(achievement.getId()));
        List<Demand> data = (List<Demand>) ajaxResult.get("data");

        if(data == null || data.isEmpty()){//推荐内容为空就不推荐
            return toAjax(save);
        }
        HashMap<String, Object> stringObjectsHashMap = new HashMap<>();
        ArrayList<Object> idsList = new ArrayList<>();
        for (Demand datum : data) {
            HashMap<String, String> tHashMap = new HashMap<>();
            tHashMap.put("id",datum.getId().toString());
            tHashMap.put("title", datum.getTitle());
            idsList.add(tHashMap);
        }
        stringObjectsHashMap.put("ids",idsList);
        stringObjectsHashMap.put("type",0);
        MyMesssage myMesssage = new MyMesssage();
        myMesssage.setUid(String.valueOf(SecurityUtils.getUserId()));
        myMesssage.setMsg(JSON.toJSONString(stringObjectsHashMap));
        myMesssage.setCmd("system");
        //amqpTemplate.convertAndSend(FanoutExchangeDemoConfig.EXCHANGE_NAME, "", myMesssage);
        return toAjax(save);
    }

    /**
     * 修改科技成果管理
     */
    @Log(title = "科技成果管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Achievement achievement) {
        // 不需要设置，因为可能是管理员修改审核状态
//        achievement.setAuthorName(SecurityUtils.getLoginUser().getSysUser().getNickName());
//        用户修改成果后，需要将成果状态置为审核中；若是管理员修改状态，则不需要
        String createBy = achievement.getCreateBy();
        String username = SecurityUtils.getUsername();
        // 假设系统管理员不能在平台上传成果
//        if (createBy.equals(username)) {
//            achievement.setState(0);
//            return warn("不可审核自己添加的成果");
//        }
        return toAjax(achievementService.updateById(achievement));
    }

    @InnerAuth  // 只能内部使用
    @PostMapping("/updateNickName")
    public AjaxResult updateNickName(@RequestBody SysUser user) {
        Achievement achievement = new Achievement();
        achievement.setAuthor(user.getUserId());
        achievement.setAuthorName(user.getNickName());
        achievementService.updateNickName(achievement);
        return AjaxResult.success();
    }

    /**
     * 删除科技成果管理
     */
    @Log(title = "科技成果管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(achievementService.removeByIds(ids));
    }

//    @Override
//    public void onMessage(Message message, Channel channel) throws Exception {
//
//    }
//
//    @Override
//    public void onMessage(Message message) {
//        ChannelAwareMessageListener.super.onMessage(message);
//    }
//
//    @Override
//    public void containerAckMode(AcknowledgeMode mode) {
//        ChannelAwareMessageListener.super.containerAckMode(mode);
//    }
//
//    @Override
//    public boolean isAsyncReplies() {
//        return ChannelAwareMessageListener.super.isAsyncReplies();
//    }
//
//    @Override
//    public void onMessageBatch(List<Message> messages) {
//        ChannelAwareMessageListener.super.onMessageBatch(messages);
//    }
//
//    @Override
//    public void onMessageBatch(List<Message> messages, Channel channel) {
//        ChannelAwareMessageListener.super.onMessageBatch(messages, channel);
//    }
}
